package com.example.Lezedata.ui.activity.login;
import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.view.View;
import android.widget.TextView;

import com.example.Lezedata.R;
import com.example.Lezedata.dataManager.GBUserManager;
import com.example.Lezedata.dataManager.LoginManager;
import com.example.Lezedata.net.GBError;
import com.example.Lezedata.net.GBNetRequest;
import com.example.Lezedata.net.ServerResponseObserver;
import com.example.Lezedata.ui.customView.CGInputAndRightView;
import com.example.Lezedata.ui.customView.CGInputView;
import com.example.Lezedata.ui.activity.baseClass.GBBaseVc;
import com.example.Lezedata.ui.tabBar.GBTabBarVc;
import com.example.Lezedata.util.GBSaveData;
import com.example.Lezedata.util.GBToast;
import com.example.Lezedata.util.GBUtil;

import java.security.NoSuchAlgorithmException;

import bid.Bid;

public class LoginVc extends GBBaseVc {
    boolean showPsd = false;
    private CGInputView textField1;
    private CGInputAndRightView textField2;
    boolean isPhoneLogin = GBSaveData.getBoolData("login_type",true);
    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public CharSequence title() {
        return "";
//        return getResources().getString(R.string.Login);
    }

    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        View button = findViewById(R.id.registerButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpActivity(RegisterVc.class);
            }
        });

        View forget = findViewById(R.id.forgetPsd);
        forget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpActivity(ForgetPsdVc.class);
            }
        });

        findViewById(R.id.commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    login();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
        });
        initView();
    }

    void initView (){
        textField1 = findViewById(R.id.mobile);
        switchLoginType(false);

        String login_psd = GBSaveData.getData("login_psd");
        textField2 = findViewById(R.id.password);
        textField2.leftView.setText(getString(R.string.Password));
        textField2.inputView.setHint(getString(R.string.EnterPassword));
        textField2.inputView.setText(login_psd);
        textField2.rightView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPsd = !showPsd;
                refreshRightView();
            }
        });
        refreshRightView();

        findViewById(R.id.switchAccountType).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPhoneLogin = !isPhoneLogin;
                switchLoginType(true);
            }
        });
    }

    void refreshRightView(){
        Drawable drawable = getResources().getDrawable(!showPsd?R.drawable.login_display:R.drawable.login_hide);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        textField2.rightView.setCompoundDrawables(null,null,drawable,null);
        if (showPsd) {
            //选择状态 显示明文--设置为可见的密码
            textField2.inputView.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            //默认状态显示密码--设置文本 要一起写才能起作用  InputType.TYPE_CLASS_TEXT | 							InputType.TYPE_TEXT_VARIATION_PASSWORD
            textField2.inputView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }

    void switchLoginType(boolean clearData){
        String login_phone_code = GBSaveData.getData("login_phone_code");
        String login_phone = GBSaveData.getData("login_phone");
        if (clearData){
            login_phone_code = "";
            login_phone = "";
        }

        if (login_phone_code == ""){
            login_phone_code = "+86";
        }
        String hint = getString(R.string.EnterMobile);
        int inputType = InputType.TYPE_CLASS_NUMBER;
        int limit = 11;
        if (!isPhoneLogin){ // 邮箱
            limit = 120;
            inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
            hint = "请输入邮箱地址";
            login_phone_code = "邮箱";
        }

        Drawable drawable = getResources().getDrawable(isPhoneLogin?R.drawable.email_type:R.drawable.phone_type);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        TextView textView = findViewById(R.id.switchAccountType);
        textView.setCompoundDrawables(null,drawable,null,null);
        textView.setText(isPhoneLogin?"邮箱登录":"手机登录");

        textField1.inputView.setHint(hint);
        textField1.leftView.setText(login_phone_code);
        textField1.inputView.setText(login_phone);
        textField1.inputView.setInputType(inputType);
        InputFilter[]inputFilter = new InputFilter[]{GBUtil.limitFilter(limit)};
        textField1.inputView.setFilters(inputFilter);
    }

    @SuppressLint("WrongConstant")
    void login() throws NoSuchAlgorithmException {
        if (GBUtil.stringIsEmpty(textField1.inputView.getText().toString())){
            GBToast.shortToast(textField1.inputView.getHint().toString());
            return;
        }
        if (GBUtil.stringIsEmpty(textField2.inputView.getText().toString())){
            GBToast.shortToast(textField2.inputView.getHint().toString());
            return;
        }
        if (isPhoneLogin){
            loginByPhone();
        }else {
            loginByEmail();
        }
    }

    void loginByEmail(){
        String pw = textField2.inputView.getText().toString();
        pw = GBUtil.getSHA256(pw);
        Bid.LoginByEmailRequest request = Bid.LoginByEmailRequest.newBuilder()
                .setEmail(textField1.inputView.getText().toString())
                .setPw(pw)
                .build();
        ServerResponseObserver observer = new ServerResponseObserver(new ServerResponseObserver.requestListener<Bid.LoginResponse>() {
            @Override
            public void complete(Bid.LoginResponse value, GBError t) {
                hudDismiss();
                if (t == null){
                    loginSuccess(value);
                }
            }
        });
        GBNetRequest.stub().loginByEmail(request,observer);
        hudShow();
    }

    void loginByPhone(){
        String pw = textField2.inputView.getText().toString();
        pw = GBUtil.getSHA256(pw);
        Bid.LoginRequest request = Bid.LoginRequest.newBuilder()
                .setPhoneCode(textField1.leftView.getText().toString())
                .setPhone(textField1.inputView.getText().toString())
                .setPw(pw)
                .build();
        ServerResponseObserver observer = new ServerResponseObserver(new ServerResponseObserver.requestListener<Bid.LoginResponse>() {
            @Override
            public void complete(Bid.LoginResponse value, GBError t) {
                hudDismiss();
                if (t == null){
                    loginSuccess(value);
                }
            }
        });
        GBNetRequest.stub().login(request,observer);
        hudShow();
    }

    void loginSuccess(Bid.LoginResponse value){
        GBSaveData.setData("login_phone_code",textField1.leftView.getText().toString());
        GBSaveData.setData("login_phone",textField1.inputView.getText().toString());
        GBSaveData.setData("login_psd",textField2.inputView.getText().toString());
        GBSaveData.setBoolData("login_type",isPhoneLogin);
        GBUserManager.instance().setLoginData(value);
        LoginManager.instance().setLoginStatus(LoginManager.LoginStatus_login);
        jumpActivity(GBTabBarVc.class);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        },1000);
    }

    @Override
    protected boolean hideNavigationBack() {
        return true;
    }
}
